package com.example.dubbo.consumer.controller;

import com.example.dubbo.api.model.User;
import com.example.dubbo.api.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * 通过 Dubbo 调用远程服务
 */
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    /**
     * 使用 @DubboReference 注入远程服务
     * Dubbo 会自动从 Nacos 获取 Provider 地址并进行 RPC 调用
     */
    @DubboReference(version = "1.0.0", timeout = 5000, check = false)
    private UserService userService;
    
    /**
     * 获取所有用户
     */
    @GetMapping
    public Map<String, Object> getAllUsers() {
        System.out.println("Consumer 请求: 获取所有用户");
        List<User> users = userService.getAllUsers();
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", users);
        result.put("count", users.size());
        result.put("message", "获取成功");
        return result;
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public Map<String, Object> getUserById(@PathVariable Long id) {
        System.out.println("Consumer 请求: 获取用户 ID=" + id);
        User user = userService.getUserById(id);
        
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            result.put("success", true);
            result.put("data", user);
            result.put("message", "获取成功");
        } else {
            result.put("success", false);
            result.put("message", "用户不存在");
        }
        return result;
    }
    
    /**
     * 创建用户
     */
    @PostMapping
    public Map<String, Object> createUser(@RequestBody User user) {
        System.out.println("Consumer 请求: 创建用户 " + user);
        User created = userService.createUser(user);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", created);
        result.put("message", "创建成功");
        return result;
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteUser(@PathVariable Long id) {
        System.out.println("Consumer 请求: 删除用户 ID=" + id);
        Boolean success = userService.deleteUser(id);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "删除成功" : "删除失败");
        return result;
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Map<String, String> health() {
        Map<String, String> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "dubbo-consumer");
        result.put("dubbo", "connected");
        return result;
    }
}

